# import time,random,threading
# from multiprocessing import Queue  # 队列
#
# def tree(q):
#     no = 1
#     while True:
#         apple = f'苹果{no}'
#         q.put(apple)
#         print(f"{time.strftime('%H:%M:%S')}：添加一个{apple}，共有{q.qsize()}个苹果.")
#         no += 1
#         time.sleep(random.randint(1,2))
#
# def eat(q,name):
#     while True:
#         print(f'{name}吃掉了{q.get()},剩余：{q.qsize()}')
#         time.sleep(random.randint(2,3))
#
# if __name__ == '__main__':
#     q = Queue(maxsize=6)
#     t=threading.Thread(target=tree,args=(q,))
#     p1 = threading.Thread(target=eat, args=(q, '张三'))
#     p2 = threading.Thread(target=eat, args=(q, '李四'))
#     t.start()
#     t.join(10)
#     p1.start()
#     p2.start()



# import time
# from threading import Thread
# def A(n,name):
#     time.sleep(n)
#     print(f"{name}运行完了")
# if __name__ == '__main__':
#     print("主进程开始的时间",time.time())
#     t1=Thread(target=A,name="线程1", args=(6,"1"),daemon=True)
#     t2=Thread(target=A,name="线程2", args=(5,"2"),)
#     t3=Thread(target=A,name="线程3", args=(3,"3"),)
#     t1.start()
#     t2.start()
#     t3.start()
#     print("主进程结束的时间", time.time())


# import time
# from threading import Thread,Lock
#
# class App(object):
#     apple = []
#     n = 1
#     def __init__(self,name):
#         self.name = name
#
#     def add(self):
#
#         while True:
#             App.apple.append(f'苹果{App.n}')
#             print(f'{self.name}添加后的列表：',App.apple)
#             App.n += 1
#             time.sleep(2)
#     def eat(self):
#         while True:
#             if len(App.apple)>0:
#                 a = App.apple.pop(0)
#                 print(f'{self.name}吃了{a}，剩下{App.apple}')
#             time.sleep(5)
#
# if __name__ == '__main__':
#
#     tree1=App('苹果树1')
#     t = Thread(target=add)
#     a1 = Thread(target=eat,args=('张三',))
#     a2 = Thread(target=eat,args=('李四',))
#     t.start()
#     t.join(5)
#     a1.start()
#     a2.start()


from threading import Thread,Lock
n=10
lock=Lock()  # 声明一个锁
def test():
    global n
    for i in range(10000):
        with lock:
            # lock.acquire()  # 获取锁，并锁定  --->其他线程不能运行
            n += 5
            n -= 5
            # lock.release()  # 释放锁 --->解锁后其他线程才能运行
if __name__ == '__main__':
    for i in range(10):
        t1 = Thread(target=test)
        t2 = Thread(target=test)
        t1.start()
        t2.start()
        t1.join()
        t2.join()
        print(n)




















